﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DelovodnaKnjiga.Repository;
using System.IO;
using System.Data.SqlClient;
using Microsoft.Win32.SafeHandles;
using System.Runtime.InteropServices;
using System.Diagnostics;
using DelovodnaKnjiga.DataLayer;
using Common.Tools;
using DevExpress.XtraEditors;
using WIA; 

namespace DelovodnaKnjiga
{
    public partial class DokumentRecView : Common.Forms.RecView
    {
        DelovodnaKnjigaDataContext dc;
        RDokument rDokument = new RDokument();
        RDokumentPrilog rDokumentPrilog = new RDokumentPrilog();
        int id;
        int delovodnikId;

        #region Refresh grid
        void RefreshGrid()
        {
            int topRowIndex = gridView1.TopRowIndex;
            int focusedRowHandle = gridView1.FocusedRowHandle;

            try
            {
                bsDokumentPrilog.DataSource = rDokumentPrilog.VratiSve(this.id);
            }
            catch (Exception ex)
            {
                Common.Tools.MessageError.Show("Greška: " + ex.Message);
            }

            gridView1.FocusedRowHandle = focusedRowHandle;
            gridView1.TopRowIndex = topRowIndex;

        }
        #endregion

        public DokumentRecView(int id, int delovodnikId)
        {
            InitializeComponent();
            this.id = id;
            this.delovodnikId = delovodnikId;
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            try
            {
                bsDokument.EndEdit();
                int i = rDokument.Snimi((Dokument)bsDokument.Current);
                this.Index = rDokument.VratiSve().ToList().FindIndex(c => c.DokumentId == i);
            }
            catch (Exception ex)
            {
                Common.Tools.MessageError.Show(ex.Message);
                this.DialogResult = DialogResult.None;
            }
        }

        private void btnBrisi_Click(object sender, EventArgs e)
        {
            if (gridView1.RowCount == 0)
            {
                Common.Tools.MessageError.ShowNePostojiSlogZaBrisanje();
                return;
            }

            if (Common.Tools.MessageQuestion.Show("Da li želite da obrišete slog?") == DialogResult.Yes)
            {
                try
                {
                    rDokumentPrilog.Brisi(((DokumentPrilog)bsDokumentPrilog.Current).DokumentPrilogId);
                    RefreshGrid();
                }
                catch (System.Data.SqlClient.SqlException s)
                {
                    if (s.Number == 547) Common.Tools.MessageError.Show("Ne možete obrisati podatak na koji postoji referenca u drugoj tabeli!");
                    else Common.Tools.MessageError.Show(s.Message);

                }
                catch (Exception ex)
                {
                    Common.Tools.MessageError.Show(ex.Message);
                }
            }
        }

        private void btnUcitaj_Click(object sender, EventArgs e)
        {
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    FileStream stream = new FileStream(openFileDialog.FileName, FileMode.Open, FileAccess.Read);
                    BinaryReader reader = new BinaryReader(stream);
                    byte[] sadrzaj = reader.ReadBytes((int)stream.Length);
                    reader.Close();
                    stream.Close();

                    DokumentPrilog prilog = new DokumentPrilog();
                    prilog.DokumentId = this.id;
                    prilog.Naziv = Path.GetFileName(openFileDialog.FileName); 
                    prilog.Tip = Path.GetExtension(openFileDialog.FileName);
                    prilog.Sadrzaj = sadrzaj;
                    prilog.KorisnikId = Common.Properties.Settings.Default.KorisnikId;
                    prilog.DatumRada = Common.Tools.SqlFunkcije.VratiTrenutnoVreme();
                    prilog.FileStreamId = Guid.NewGuid();

                    dc.DokumentPrilogs.InsertOnSubmit(prilog);
                    dc.SubmitChanges();
                    RefreshGrid();
                    Common.Tools.MessageInformation.Show("Dokument je uspešno učitan!");
                }
                catch (Exception ex)
                {
                    Common.Tools.MessageError.Show(ex.Message);
                }
            }
        }

        private void btnPregledaj_Click(object sender, EventArgs e)
        {
            if (gridView1.RowCount == 0)
            {
                Common.Tools.MessageError.Show("Ne postoji slog za prikaz!");
                return;
            }
            try
            {
                string folder;
                folder = Common.Tools.Parametar.Citaj("Global", "FolderZasnimanje");
                byte[] buffer = ((DokumentPrilog)bsDokumentPrilog.Current).Sadrzaj.ToArray();
                FileStream fs = new FileStream(folder + ((DokumentPrilog)bsDokumentPrilog.Current).Naziv, FileMode.Create);
                fs.Write(buffer, 0, buffer.Length);
                fs.Close();
                Process.Start(folder + ((DokumentPrilog)bsDokumentPrilog.Current).Naziv);
            }
            catch (Exception ex)
            {
                Common.Tools.MessageError.Show(ex.Message);
            }
        }

        private void DokumentRecView_Load(object sender, EventArgs e)
        {
            RDokumentTip rDokumentTip = new RDokumentTip();
            bsDokumentTip.DataSource = rDokumentTip.VratiSveAktivne();

            RDelovodnik rDelovodnik = new RDelovodnik();
            bsDelovodnik.DataSource = rDelovodnik.VratiSveAktivne();

            RZaposleni rZaposleni = new RZaposleni();
            bsZaposleni.DataSource = rZaposleni.VratiSve();

            if (id == 0)
            {
                if (this.delovodnikId == 0)
                    bsDokument.DataSource = rDokument.Nov();
                else
                    bsDokument.DataSource = rDokument.Nov(this.delovodnikId);
               
                btnUcitaj.Enabled = false;
                btnSkeniraj.Enabled = false;
                btnBrisi.Enabled = false;
                btnPregledaj.Enabled = false;
            }
            else
            {
                bsDokument.DataSource = rDokument.Izmeni(this.id);
                btnUcitaj.Enabled = true;
                btnSkeniraj.Enabled = true;
                btnBrisi.Enabled = true;
                btnPregledaj.Enabled = true;
            }

            RefreshGrid();

            dc = new DelovodnaKnjigaDataContext();

            // Morao sam ovako da uradim pošto komponenta RadioGroup ima neki bug
            rgVrstaDokumenta.Properties.Items.Clear();
            rgVrstaDokumenta.Properties.Items.AddRange(new DevExpress.XtraEditors.Controls.RadioGroupItem[] {
            new DevExpress.XtraEditors.Controls.RadioGroupItem(1, "Ulazni"),
            new DevExpress.XtraEditors.Controls.RadioGroupItem(2, "Izlazni")});

            Common.MultiLanguage.Tool.PrevediFormu(this);
        }

        private void btnSkeniraj_Click(object sender, EventArgs e)
        {
            try
            {
                string naziv = "";
                if (Common.Tools.InputBox.Show("Unesite naziv dokumenta", "Naziv dokumenta:", ref naziv) == DialogResult.OK)
                {
                    const string wiaFormatJPEG = "{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}";
                    WIA.CommonDialog wiaDiag = new WIA.CommonDialog();
                    WIA.ImageFile wiaImage = null;

                    wiaImage = wiaDiag.ShowAcquireImage(
                            WiaDeviceType.UnspecifiedDeviceType,
                            WiaImageIntent.GrayscaleIntent,
                            WiaImageBias.MaximizeQuality,
                            wiaFormatJPEG, true, true, false);

                    WIA.Vector vector = wiaImage.FileData;

                    byte[] sadrzaj = (byte[])vector.get_BinaryData();

                    DokumentPrilog prilog = new DokumentPrilog();
                    prilog.DokumentId = this.id;
                    prilog.Naziv = naziv + ".jpg";
                    prilog.Tip = ".jpg";
                    prilog.Sadrzaj = sadrzaj;
                    prilog.KorisnikId = Common.Properties.Settings.Default.KorisnikId;
                    prilog.DatumRada = Common.Tools.SqlFunkcije.VratiTrenutnoVreme();
                    prilog.FileStreamId = Guid.NewGuid();

                    dc.DokumentPrilogs.InsertOnSubmit(prilog);
                    dc.SubmitChanges();
                }
            }
            catch (Exception ex)
            {
                Common.Tools.MessageError.Show(ex.Message);
            }
        }
    }
}
